<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :element-loading-text="global.loadingStr"
      :header-cell-style="{ background: global.mainColor }"
    >
      <el-table-column label="序号" align="center" width="100" fixed>
        <template slot-scope="{ $index }">
          <span>{{
            $index + 1 + (listQuery.currentPage - 1) * listQuery.pageSize
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商户LOGO" align="center">
        <template slot-scope="{ row }">
          <span><img :src="row.logoImg" alt="" class="table-row-img" /></span>
        </template>
      </el-table-column>
      <el-table-column label="机构名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构开业时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.foundTime | parseTime("{y}-{m}-{d}")  }}</span>
        </template>
      </el-table-column>      
      <el-table-column label="机构地址" align="center">
        <template slot-scope="{ row }">
          <span
            >{{ row.province }}{{ row.city }}{{ row.region }}{{ row.town
            }}{{ row.detail }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="商户负责人" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.principalName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" width="120px">
        <template slot-scope="{ row }">
          <span>{{ row.serverPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经营范围" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.categoryNames }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入驻时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime("{y}-{m}-{d} {h}:{i}") }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="editBusinessProfile = true">
            修改资料
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="商户编辑"
      :visible.sync="editBusinessProfile"
      width="1200px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="商户logo">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :class="{ hide: hideUpload }"
            :file-list="imgsList"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="商户小图标">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-remove="handleRemoveIcon"
            :on-change="handleChangeIcon"
            :auto-upload="false"
            :class="{ hide: hideUploadIcon }"
            :file-list="imgsListIcon"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item> -->
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item label="机构开业时间" prop="name">
          <el-date-picker v-model="form.foundTime" type="date" value-format="timestamp" placeholder="选择开业时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="机构地址">
          <el-cascader
            v-model="selectedOptions"
            size="large"
            :options="areaOptions"
            style="width: 240px"
            @change="areaChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" clearable />
          <el-button type="text" @click="addressOptions.dialog = true"
            >位置调整</el-button
          >
        </el-form-item>
        <el-form-item label="商户负责人" prop="principalName">
          <el-input v-model="form.principalName" clearable />
        </el-form-item>
        <el-form-item label="商户负责人手机号" prop="serverPhone">
          <el-input v-model="form.serverPhone" clearable />
        </el-form-item>
        <el-form-item label="设施标签">
          <el-checkbox
            v-model="checkFacilityLabelAll"
            :indeterminate="isFacilityLabelIndeterminate"
            @change="handlecheckFacilityLabelAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="hasChoosebackstageFacilityLabels"
            @change="handleCheckedFacilityLabelsChange"
          >
            <el-checkbox
              v-for="item in backstageFacilityLabels"
              :key="item.id"
              :label="item.name"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="周围环境标签">
          <el-checkbox
            v-model="checkEnvironmentLabelAll"
            :indeterminate="isEnvironmentLabelIndeterminate"
            @change="handlecheckEnvironmentLabelAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="hasChoosebackstageEnvironmentLabels"
            @change="handleCheckedEnvironmentLabelsChange"
          >
            <el-checkbox
              v-for="item in backstageEnvironmentLabels"
              :key="item.id"
              :label="item.name"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="机构经营范围">
          <el-tabs
            v-model="topTypeIndex"
            style="position: relative; top: -2px"
            @tab-click="topTypeClick"
          >
            <el-tab-pane
              v-for="(item, index) in topTypeList"
              :key="item.id"
              :label="item.name"
              :name="index + ''"
            >
              <el-checkbox
                v-model="checkTypeAll"
                :indeterminate="isTypeIndeterminate"
                @change="handlecheckTypeAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group
                v-model="chooseTypes"
                @change="handleCheckedTypesChange"
              >
                <el-checkbox
                  v-for="row in childrenType"
                  :key="row.name"
                  :label="row.name"
                  >{{ row.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="机构详情">
          <tinymce v-model="form.synopsis" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editBusinessProfile = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="选择地址"
      :visible.sync="addressOptions.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="750px"
      @close="1"
    >
      <div ref="mapArry" style="width: 100%; height: 600px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY&referer=myapp"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressOptions.dialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from "@/directive/waves";
import Pagination from "@/components/Pagination";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import {
  merchantDetail,
  merchantUpdate,
  merchantType,
  getAllLabels,
  merchantAllType,
  merchantList,
  merchantStatus,
} from "@/api/account";
import Tinymce from "@/components/Tinymce";

export default {
  name: "MerchantList",
  directives: { waves },
  components: { Pagination, Tinymce },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        keyword: "",
        isCertified: true,
        status: "2",
        province: "",
        city: "",
        region: "",
        town: "",
      },
      editBusinessProfile: false,
      rules: {
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.global.checkInputIsEmpty,
          },
        ],
        detail: [
          {
            required: true,
            trigger: "blur",
            validator: this.global.checkInputIsEmpty,
          },
        ],
        principalName: [
          {
            required: true,
            trigger: "blur",
            validator: this.global.checkInputIsEmpty,
          },
        ],
        serverPhone: [
          {
            required: true,
            trigger: "blur",
            validator: this.global.checkInputIsEmpty,
          },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "目前只支持中国大陆的手机号码",
          },
        ],
      },
      form: {
        id: "",
        name: "",
        logoImg: null,
        icon: null,
        lat: "",
        lng: "",
        addressIds: "",
        province: "",
        city: "",
        region: "",
        detail: "",
        principalName: "",
        serverPhone: "",
        categoryIds: [],
        categoryNames: [],
        categoryParentIds: [],
        categoryParentNames: [],
        synopsis: "",
        classify: "",
        labels: "",
        foundTime:''
      },
      imgsList: [],
      hideUpload: false,
      imgFile: null,

      imgsListIcon: [],
      hideUploadIcon: false,
      imgFileIcon: null,

      areaOptions: regionData,
      selectedOptions: [],

      topTypeIndex: "0",
      allTypeList: [],
      topTypeList: [],
      childrenType: [],
      chooseTypes: [],
      checkTypeAll: false,
      isTypeIndeterminate: true,

      checkFacilityLabelAll: false,
      isFacilityLabelIndeterminate: false,
      backstageFacilityLabels: [],
      hasChoosebackstageFacilityLabels: [],

      checkEnvironmentLabelAll: false,
      isEnvironmentLabelIndeterminate: false,
      backstageEnvironmentLabels: [],
      hasChoosebackstageEnvironmentLabels: [],

      addressOptions: {
        dialog: false,
        address: "",
        lat: "",
        lng: "",
      },
    };
  },
  created() {
    this.form.id = localStorage.getItem("businessId");
    this.refresh();
    this.refreshAllType();
    this.refreshFacilityLabelList();
    this.refreshEnvironmentLabelList();
  },
  mounted() {
    const that = this;
    // 为了防止火狐浏览器拖拽的时候以新标签打开
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    window.addEventListener(
      "message",
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module === "locationPicker") {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          console.log("location", loc);
          that.form.lat = loc.latlng.lat;
          that.form.lng = loc.latlng.lng;
          that.form.detail = loc.poiname;
        }
      },
      false
    );
    this.listQuery.keyword = localStorage.getItem("businessName");
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      const data = {};
      for (const item of Object.keys(this.listQuery)) {
        data[item] = this.listQuery[item];
      }
      data["isCertified"] = data["isCertified"] ? 1 : 0;
      data["province"] = data["province"] === "全部" ? "" : data["province"];
      merchantList(data).then((response) => {
        console.log(response.data);
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleUpdate(row) {
      this.editBusinessProfile = true;
    },
    refresh() {
      merchantDetail({ businessId: this.form.id }).then((response) => {
        console.log(response);
        const data = response.data;
        if (data.logoImg !== null && data.logoImg !== "") {
          this.imgsList = [{ url: data.logoImg }];
          this.hideUpload = true;
        }
        this.form.logoImg = data.logoImg;

        if (data.icon !== null && data.icon !== "") {
          this.imgsListIcon = [{ url: data.icon }];
          this.hideUploadIcon = true;
        }
        this.form.logoImgIcon = data.icon;
        this.form.foundTime = data.foundTime
        this.form.name = data.name;
        this.form.province = data.province;
        this.form.city = data.city;
        this.form.region = data.region;
        this.form.addressIds = data.addressIds;
        this.selectedOptions = [];
        if (
          typeof TextToCode[data.province] !== "undefined" &&
          typeof TextToCode[data.province][data.city] !== "undefined" &&
          typeof TextToCode[data.province][data.city][data.region] !==
            "undefined"
        ) {
          this.selectedOptions.push(TextToCode[data.province].code + "");
          this.selectedOptions.push(
            TextToCode[data.province][data.city].code + ""
          );
          this.selectedOptions.push(
            TextToCode[data.province][data.city][data.region].code + ""
          );
        }

        this.form.detail = data.detail;
        this.form.principalName = data.principalName;
        this.form.serverPhone = data.serverPhone;
        this.form.synopsis = data.synopsis;

        if (data.backstageLabels !== null) {
          data.backstageLabels.map((item) => {
            if (item["type"] === 1) {
              this.hasChoosebackstageFacilityLabels.push(item["name"]);
            }
            if (item["type"] === 2) {
              this.hasChoosebackstageEnvironmentLabels.push(item["name"]);
            }
          });
          console.log("设施标签");
          console.log(this.hasChoosebackstageFacilityLabels);
          console.log("环境标签");
          console.log(this.hasChoosebackstageEnvironmentLabels);
        }

        this.chooseTypes =
          data.categoryNames === null ? [] : data.categoryNames.split(",");
        this.refreshTopType();
      });
    },
    handlecheckTypeAllChange(val) {
      if (val) {
        for (const item of this.childrenType) {
          this.chooseTypes.push(item["name"]);
        }
        const setList = new Set(this.chooseTypes);
        this.chooseTypes = Array.from(setList);
      } else {
        for (const item of this.childrenType) {
          this.chooseTypes.splice(this.chooseTypes.indexOf(item), 1);
        }
      }
      this.isTypeIndeterminate = false;
    },
    handleCheckedTypesChange(value) {
      const checkedCount = value.length;
      this.checkTypeAll = checkedCount === this.childrenType.length;
      this.isTypeIndeterminate =
        checkedCount > 0 && checkedCount < this.childrenType.length;
    },
    areaChange(value) {
      console.log(value);
      const province = CodeToText[value[0]];
      const city = CodeToText[value[1]];
      const region = CodeToText[value[2]];
      this.form.province = province;
      this.form.city = city;
      this.form.region = region;

      const addressIdsList = [value[0], value[1], value[2]];
      this.form.addressIds = addressIdsList.join(",");
      console.log(this.selectedOptions);
    },
    refreshAllType() {
      merchantAllType().then((response) => {
        this.allTypeList = response.data;
      });
    },
    refreshTopType() {
      merchantType({
        flagEnable: 1,
      }).then((response) => {
        console.log(response);
        this.topTypeList = response.data;
        this.refreshChildrenType(this.topTypeList[0]["id"]);
      });
    },
    topTypeClick(tab, event) {
      console.log(tab, event);
      this.topTypeIndex = tab.name;
      this.refreshChildrenType(
        this.topTypeList[parseInt(this.topTypeIndex)]["id"]
      );
    },
    refreshChildrenType(parentId) {
      merchantType({
        parentId: parentId,
        flagEnable: 1,
      }).then((response) => {
        console.log("子分类", this.chooseTypes);
        console.log(response);
        this.childrenType = response.data;
        let count = 0;
        for (const item of this.childrenType) {
          for (const row of this.chooseTypes) {
            if (item["name"] === row) {
              count++;
            }
          }
        }
        this.checkTypeAll = count === this.childrenType.length;
        this.isTypeIndeterminate =
          count > 0 && count < this.childrenType.length;
      });
    },
    async submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.goToSubmit();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async goToSubmit() {
      if (this.imgFile === null && this.form.logoImg === null) {
        this.$message({ message: "请选择图片", type: "error" });
        return;
      }

      if (this.imgFile !== null) {
        await this.uploadImgToOss(this.imgFile).then((response) => {
          console.log("图片上传结果：" + JSON.stringify(response));
          this.form.logoImg = response.imgUrl;
        });
      }

      if (this.imgFileIcon !== null) {
        await this.uploadImgToOss(this.imgFileIcon).then((response) => {
          console.log("图片上传结果：" + JSON.stringify(response));
          this.form.icon = response;
        });
      }

      const categoryIds = [];
      let categoryParentIds = [];
      let categoryParentNames = [];

      let hasClassify1 = false;
      let hasClassify2 = false;
      this.allTypeList.forEach((parentItem) => {
        for (const item of parentItem["categories"]) {
          for (const row of this.chooseTypes) {
            if (item["name"] === row && item["classify"] === 1) {
              hasClassify1 = true;
            }
            if (item["name"] === row && item["classify"] === 2) {
              hasClassify2 = true;
            }
            if (row === item["name"]) {
              categoryIds.push(item["id"]);
              categoryParentIds.push(parentItem["id"]);
              categoryParentNames.push(parentItem["name"]);
            }
          }
        }
      });

      const setCategoryParentIds = new Set(categoryParentIds);
      categoryParentIds = Array.from(setCategoryParentIds);

      const setCategoryParentNames = new Set(categoryParentNames);
      categoryParentNames = Array.from(setCategoryParentNames);

      this.form.classify =
        hasClassify1 && hasClassify2
          ? 3
          : hasClassify1
          ? 1
          : hasClassify2
          ? 2
          : null;
      this.form.categoryIds =
        categoryIds.length > 0 ? categoryIds.join(",") : "";
      this.form.categoryNames =
        this.chooseTypes.length > 0 ? this.chooseTypes.join(",") : "";
      this.form.categoryParentIds =
        categoryParentIds.length > 0 ? categoryParentIds.join(",") : "";
      this.form.categoryParentNames =
        categoryParentNames.length > 0 ? categoryParentNames.join(",") : "";

      console.log("allTypeList：", this.allTypeList);
      console.log("categoryIds：", categoryIds);
      console.log("categoryNames：", this.form.categoryNames);
      console.log("categoryParentIds：", categoryParentIds);
      console.log("categoryParentNames：", categoryParentNames);

      const labelIds = [];
      for (const item of this.backstageFacilityLabels) {
        for (const row of this.hasChoosebackstageFacilityLabels) {
          if (item["name"] === row) {
            labelIds.push(item["id"]);
          }
        }
      }
      for (const item of this.backstageEnvironmentLabels) {
        for (const row of this.hasChoosebackstageEnvironmentLabels) {
          if (item["name"] === row) {
            labelIds.push(item["id"]);
          }
        }
      }
      this.form.labels = labelIds.join(",");
      merchantUpdate(this.form).then((response) => {
        this.$message({ message: "提交成功", type: "success" });
        this.editBusinessProfile = false;
        this.getList();
      });
    },
    handleRemove(file, fileList) {
      console.log("handleChange");
      console.log(file);
      this.hideUpload = false;
    },
    handleChange(file, fileList) {
      console.log("handleChange" + fileList.length);
      console.log(file);
      this.imgFile = fileList.length > 0 ? file : null;
      this.hideUpload = fileList.length >= 1;
    },
    handleRemoveIcon(file, fileList) {
      console.log("handleChange");
      console.log(file);
      this.hideUploadIcon = false;
    },
    handleChangeIcon(file, fileList) {
      console.log("handleChange" + fileList.length);
      console.log(file);
      this.imgFileIcon = fileList.length > 0 ? file : null;
      this.hideUploadIcon = fileList.length >= 1;
    },
    refreshFacilityLabelList() {
      getAllLabels({
        status: 1,
        type: 1,
      }).then((response) => {
        console.log(response);
        this.backstageFacilityLabels = response["data"];

        const checkedCount = this.hasChoosebackstageFacilityLabels.length;
        this.checkFacilityLabelAll =
          checkedCount === this.backstageFacilityLabels.length;
        this.isFacilityLabelIndeterminate =
          checkedCount > 0 &&
          checkedCount < this.backstageFacilityLabels.length;
      });
    },
    handlecheckFacilityLabelAllChange(val) {
      if (val) {
        this.hasChoosebackstageFacilityLabels = [];
        this.backstageFacilityLabels.map((item) => {
          this.hasChoosebackstageFacilityLabels.push(item["name"]);
        });
      } else {
        this.hasChoosebackstageFacilityLabels = [];
      }

      this.isFacilityLabelIndeterminate = false;
    },
    handleCheckedFacilityLabelsChange(value) {
      const checkedCount = value.length;
      this.checkFacilityLabelAll =
        checkedCount === this.backstageFacilityLabels.length;
      this.isFacilityLabelIndeterminate =
        checkedCount > 0 && checkedCount < this.backstageFacilityLabels.length;
    },
    refreshEnvironmentLabelList() {
      getAllLabels({
        status: 1,
        type: 2,
      }).then((response) => {
        console.log(response);
        this.backstageEnvironmentLabels = response["data"];

        const checkedCount = this.hasChoosebackstageEnvironmentLabels.length;
        this.checkEnvironmentLabelAll =
          checkedCount === this.backstageEnvironmentLabels.length;
        this.isEnvironmentLabelIndeterminate =
          checkedCount > 0 &&
          checkedCount < this.backstageEnvironmentLabels.length;
      });
    },
    handlecheckEnvironmentLabelAllChange(val) {
      if (val) {
        this.hasChoosebackstageEnvironmentLabels = [];
        this.backstageEnvironmentLabels.map((item) => {
          this.hasChoosebackstageEnvironmentLabels.push(item["name"]);
        });
      } else {
        this.hasChoosebackstageEnvironmentLabels = [];
      }

      this.isEnvironmentLabelIndeterminate = false;
    },
    handleCheckedEnvironmentLabelsChange(value) {
      const checkedCount = value.length;
      this.checkEnvironmentLabelAll =
        checkedCount === this.backstageEnvironmentLabels.length;
      this.isEnvironmentLabelIndeterminate =
        checkedCount > 0 &&
        checkedCount < this.backstageEnvironmentLabels.length;
    },
  },
};
</script>


<style lang="scss" scoped>
.table-row-img {
  width: 100px;
  height: 100px;
  object-fit: contain;
}
</style>